import { Controller } from 'egg';
import axios from 'axios';
import * as queryString from 'querystring';
import * as cheerio from 'cheerio';

class CheerilController extends Controller {
    /**
     * 创建axios
     */
    public async createAxios(headers: any) {
        const instance = axios.create({
            baseURL: 'http://jwxt.gdufe.edu.cn/',
            headers: headers
        })
        return instance;
    }

    /**
     * 获取cookie
     */
    public async getCookie() {
        const headers: any = {
            'Content-Type': 'application/x-www-form-urlencoded',
        }
        const axiosTemp = await this.createAxios(headers);
        const result: any = await axiosTemp.get('jsxsd/');
        if (result.status === 200) {
            const cookie = result.headers['set-cookie'][0].split(';')[0];
            return cookie;
        } else {
            throw new Error(JSON.stringify({ code: 2, msg: '获取cookie失败' }));
        }
    }

    /**
     * 广才用户登录
     */
    public async gcLogin(param: any) {
        const headers: any = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cookie': param.cookie
        }
        const axiosTemp = await this.createAxios(headers);
        const submitData: any = {};
        submitData.USERNAME = param.student_id;
        submitData.PASSWORD = param.student_password;
        const result: any = await axiosTemp.post('jsxsd/xk/LoginToXkLdap', queryString.stringify(submitData));
        if (result.status === 200) {
            if (result.request.path === "/jsxsd/framework/xsMain.jsp") {
                return true;
            } else {
                throw new Error(JSON.stringify({ code: 2, msg: '登录失败，账号或密码错误' }));
            }
        } else {
            throw new Error(JSON.stringify({ code: 2, msg: '登录失败，账号或密码错误' }));
        }
    }

    /**
     * 广才用户注册
     */
    public async gcRegister() {
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                student_id: 'string',
                student_password: 'string',
                openid: 'string'
            }, request.body)
        } catch (e) {
            ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        const cookie = await this.getCookie();
        const submitData: any = {};
        submitData.cookie = cookie;
        submitData.student_id = request.body.student_id;
        submitData.student_password = request.body.student_password;
        const loginStatus = await this.gcLogin(submitData);
        if (loginStatus) {
            const headers: any = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Cookie': cookie
            }
            const axiosTemp = await this.createAxios(headers);
            const result: any = await axiosTemp.get('jsxsd/grxx/xsxx?Ves632DSdyV=NEW_XSD_XJCJ');
            if (result.status === 200) {
                const data = result.data;
                const returnData: any = await this.getPageInfoByCheerio(data);
                returnData.user_student_id = submitData.student_id;
                returnData.user_openId = request.body.openid;
                const registerResult = await this.service.userService.gcUserRegister(returnData);
                ctx.body = ctx.helper.responseSuccess('注册成功', registerResult);
            } else {
                throw new Error(JSON.stringify({ code: 2, msg: '获取学籍表失败' }));
            }
        }
    }

    /**
     * 利用爬虫爬取页面信息
     */
    public async getPageInfoByCheerio(html: any) {
        const $ = cheerio.load(html);
        const student_name_text = $('#Top1_divLoginName').text();
        const student_name = student_name_text.substr(0, student_name_text.length - 13);
        let college_name = '';
        let sex = '';
        let phone = '';
        let student_year = '';
        let age_limit = 0;
        const trArr = $('#xjkpTable').children('tbody').children('tr');
        for (let i = 0; i < trArr.length; i++) {
            if (i == 2) {
                const children = $(trArr[i]).children('td');
                college_name = $(children[0]).text();
                college_name = college_name.substr(3, college_name.length);
                const age_limit_temp = $(children[2]).text();
                age_limit = Number(age_limit_temp.substr(3, age_limit_temp.length));
            }
            if (i == 3) {
                const children = $(trArr[i]).children('td');
                sex = $(children[3]).text();
                sex = sex.replace(/(^\s*)/g, "");
            }
            if (i == 4) {
                const children = $(trArr[i]).children('td');
                phone = $(children[5]).text();
                phone = phone.replace(/(^\s*)/g, "");
            }
            if (i == 42) {
                const children = $(trArr[i]).children('td');
                student_year = $(children[1]).text();
                student_year = student_year.replace(/(^\s*)/g, "");
                student_year = student_year.substr(0, 4);
            }
        }
        let user_sex = '';
        if (sex == "男") {
            user_sex = '1';
        } else if (sex == "女") {
            user_sex = '2';
        }
        const school: any = await this.service.userService.getSchoolIdAndCollegeList({ college_name, age_limit });
        const returnData: any = {
            user_nickname: student_name,
            user_phone: phone,
            user_sex,
            user_school_id: school.school_id,
            user_college_id: school.college_id,
            user_school_year: student_year
        }
        return returnData;
    }


}
export default CheerilController;